import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { hasPermissionForPath, initializeDynamicRoutes } from '@/router/dynamic'

// 基础路由（无需权限）
const baseRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
      hidden: true
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/404.vue'),
    meta: {
      title: '页面不存在',
      hidden: true
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '',
        name: 'DashboardHome',
        component: () => import('@/views/dashboard/index.vue'),
        meta: {
          title: '仪表盘',
          icon: 'DashboardOutlined'
        }
      }
    ]
  },
  // 帖子管理相关隐藏路由
  {
    path: '/circles/post/add',
    name: 'CirclePostAdd',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '',
        name: 'CirclePostAddPage',
        component: () => import('@/views/circles/post/form/index.vue'),
        meta: {
          title: '新增帖子',
          hidden: true,
          permission: 'circle:post:add'
        }
      }
    ],
    meta: {
      title: '新增帖子',
      hidden: true,
      permission: 'circle:post:add'
    }
  },
  {
    path: '/circles/post/edit/:id',
    name: 'CirclePostEdit',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '',
        name: 'CirclePostEditPage',
        component: () => import('@/views/circles/post/form/index.vue'),
        meta: {
          title: '编辑帖子',
          hidden: true,
          permission: 'circle:post:edit'
        }
      }
    ],
    meta: {
      title: '编辑帖子',
      hidden: true,
      permission: 'circle:post:edit'
    }
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  // 404路由必须放在最后，作为兜底
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...baseRoutes]
})

// 简化的全局前置守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  const token = authStore.token
  
  // 白名单路由（无需登录）
  const whiteList = ['/login', '/404']
  
  // 隐藏路由白名单（需要登录但不需要权限验证）
  const hiddenRoutes = ['/circles/post/add', '/circles/post/edit']
  
  // 检查是否为隐藏路由（支持动态参数）
  const isHiddenRoute = hiddenRoutes.some(route => {
    if (route.includes(':')) {
      // 处理动态路由，如 /circles/post/edit/:id
      const pattern = route.replace(/:[\w]+/g, '[^/]+')
      const regex = new RegExp(`^${pattern}(/.*)?$`)
      return regex.test(to.path)
    }
    return to.path.startsWith(route)
  })

  if (!token) {
    // 未登录用户
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
    return
  }

  // 已登录用户
  if (to.path === '/login') {
    next('/dashboard')
    return
  }

  // 对于白名单路由，直接通过
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 对于dashboard，直接通过
  if (to.path === '/dashboard') {
    next()
    return
  }
  
  // 对于隐藏路由，只需要登录即可，不需要权限验证
  if (isHiddenRoute) {
    next()
    return
  }

  // 检查是否有该路径的权限（动态路由）
  let hasPermission = hasPermissionForPath(to.path)
  
  // 如果没有权限，可能是页面刷新导致动态路由丢失，尝试重新初始化
  if (!hasPermission) {
    try {
      const result = await initializeDynamicRoutes(router)
      if (result.success) {
        hasPermission = hasPermissionForPath(to.path)
      }
    } catch (error) {
      console.error('动态路由重新初始化失败:', error)
    }
  }
  
  if (!hasPermission) {
    next('/404')
    return
  }

  next()
})

export default router
